package vip.idiy.anwei_android_iot.utils.dbHandle;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import vip.idiy.anwei_android_iot.domin.DeviceData;
import vip.idiy.anwei_android_iot.domin.DeviceInfo;
import vip.idiy.anwei_android_iot.utils.DatabaseUtil;

/**
 * ClassName DeviceInfoHandle
 * describe:
 * Created: 勇
 * Email:118085890@qq.com
 * Version: 1.0
 * Create in 11:00 2023/4/22
 */
public class DeviceInfoHandle {
    private final String TAG = "myTag " + " DeviceInfoHandle ";

    private DatabaseUtil databaseUtil;

    private final String DATA_TABLE = "device_info";
    // 每页返回记录数
    private final int LIMIT = 15;


    private final String COLUMNS_INFO_ID = "info_id";
    private final String COLUMNS_DEVICE_ID = "device_id";
    private final String COLUMNS_TYPE_ID = "type_id";
    private final String COLUMNS_SCENE_ID = "scene_id";
    private final String COLUMNS_FIRMWARE_VERSION = "firmware_version";
    private final String COLUMNS_ON_LINE = "on_line";
    private final String COLUMNS_RSSI = "rssi";
    private final String COLUMNS_DATA = "device_data";

    private final String SELECT_DEVICE_ID = "device_id = ? ";
    private final String SELECT_BY_INFO_ID = "info_id = ? ";

    // 暂时不需类型的父类型
    private final String SELECT_LIST_SQL =
            "SELECT device_info.info_id, device_info.device_id, device_info.type_id, device_info.scene_id, device_info.firmware_version, device_info.on_line, device_info.rssi, device_info.device_data, device_type.type_name, device_type.type_img, device_scene.scene_name, device_scene.scene_icon " +
                    "FROM device_info " +
                    "LEFT JOIN device_type ON device_info.type_id = device_type.type_id " +
                    "LEFT JOIN device_scene ON device_info.scene_id = device_scene.scene_id";

    public DeviceInfoHandle(DatabaseUtil databaseUtil) {
        this.databaseUtil = databaseUtil;
    }

    /**
     * 添加数据
     *
     * @param deviceInfo
     * @return
     */
    public boolean insert(DeviceInfo deviceInfo) {
        ContentValues values = new ContentValues();
        values.put(COLUMNS_DEVICE_ID, deviceInfo.getDeviceId());
        values.put(COLUMNS_TYPE_ID, deviceInfo.getTypeId());
        values.put(COLUMNS_SCENE_ID, deviceInfo.getSceneId());
        values.put(COLUMNS_FIRMWARE_VERSION, deviceInfo.getFirmwareVersion());
        values.put(COLUMNS_ON_LINE, deviceInfo.isOnLine() ? 1 : 0);
        values.put(COLUMNS_RSSI, deviceInfo.getRssi());
        values.put(COLUMNS_DATA, deviceInfo.getDeviceData());
        return databaseUtil.insert(DATA_TABLE, values) > 0;
    }

    /**
     * 更新数据
     *
     * @param deviceInfo
     * @return
     */
    public boolean update(DeviceInfo deviceInfo) {
        ContentValues values = new ContentValues();
        values.put(COLUMNS_DEVICE_ID, deviceInfo.getDeviceId());
        values.put(COLUMNS_TYPE_ID, deviceInfo.getTypeId());
        values.put(COLUMNS_SCENE_ID, deviceInfo.getSceneId());
        values.put(COLUMNS_FIRMWARE_VERSION, deviceInfo.getFirmwareVersion());
        values.put(COLUMNS_ON_LINE, deviceInfo.isOnLine() ? 1 : 0);
        values.put(COLUMNS_RSSI, deviceInfo.getRssi());
        if(deviceInfo.getDeviceData()!= null){
            values.put(COLUMNS_DATA, deviceInfo.getDeviceData());
        }

        return databaseUtil.update(DATA_TABLE, values, SELECT_BY_INFO_ID, new String[]{String.valueOf(deviceInfo.getInfoId())}) > 0;
    }

    /**
     * 删除数据
     *
     * @param deviceInfo
     * @return
     */
    public boolean delete(DeviceInfo deviceInfo) {
        return databaseUtil.delete(DATA_TABLE, SELECT_DEVICE_ID, new String[]{String.valueOf(deviceInfo.getDeviceId())}) > 0;
    }

    /**
     * 根据设备ID获取数据
     *
     * @param deviceId
     * @return
     */
    public DeviceInfo selectByDeviceId(String deviceId) {
        // Cursor cursor = databaseUtil.query(DATA_TABLE,
        //         new String[]{COLUMNS_INFO_ID,
        //                 COLUMNS_DEVICE_ID,
        //                 COLUMNS_TYPE_ID,
        //                 COLUMNS_SCENE_ID,
        //                 COLUMNS_FIRMWARE_VERSION,
        //                 COLUMNS_ON_LINE,
        //                 COLUMNS_RSSI,
        //                 COLUMNS_DATA},
        //         SELECT_DEVICE_ID,
        //         new String[]{deviceId}, null, null, null);
        StringBuilder selectionBuilder = new StringBuilder();
        selectionBuilder.append(SELECT_LIST_SQL);
        selectionBuilder.append(" WHERE ").append(SELECT_DEVICE_ID);
        Cursor cursor = databaseUtil.rawQuery(selectionBuilder.toString(), new String[] {deviceId});
        DeviceInfo deviceInfo = new DeviceInfo();
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex("info_id");
            if (columnIndex >= 0) {
                deviceInfo.setInfoId(cursor.getInt(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("device_id");
            if (columnIndex >= 0) {
                deviceInfo.setDeviceId(cursor.getString(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("type_id");
            if (columnIndex >= 0) {
                deviceInfo.setTypeId(cursor.getInt(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("scene_id");
            if (columnIndex >= 0) {
                deviceInfo.setSceneId(cursor.getInt(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("firmware_version");
            if (columnIndex >= 0) {
                deviceInfo.setFirmwareVersion(cursor.getString(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("on_line");
            if (columnIndex >= 0) {
                deviceInfo.setOnLine(cursor.getInt(columnIndex) == 1);
            }
            columnIndex = cursor.getColumnIndex("rssi");
            if (columnIndex >= 0) {
                deviceInfo.setRssi(cursor.getInt(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("device_data");
            if (columnIndex >= 0) {
                deviceInfo.setDeviceData(cursor.getString(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("type_name");
            if (columnIndex >= 0) {
                deviceInfo.setTypeName(cursor.getString(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("type_img");
            if (columnIndex >= 0) {
                deviceInfo.setTypeImg(cursor.getString(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("scene_name");
            if (columnIndex >= 0) {
                deviceInfo.setSceneName(cursor.getString(columnIndex));
            }
            columnIndex = cursor.getColumnIndex("scene_icon");
            if (columnIndex >= 0) {
                deviceInfo.setSceneIcon(cursor.getString(columnIndex));
            }
        }
        return deviceInfo;
    }


    /**
     * 数据是否存在
     *
     * @param deviceId
     * @return
     */
    public boolean isExist(String deviceId) {
        Cursor cursor = null;
        try {
            String[] columns = new String[]{COLUMNS_DEVICE_ID};
            String[] selectionArgs = new String[]{deviceId};
            cursor = databaseUtil.query(DATA_TABLE, columns, SELECT_DEVICE_ID, selectionArgs, null, null, null);
            return cursor.getCount() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return false;
    }

    /**
     * 获取数据列表
     *
     * @param columnValues
     * @return
     */
    public List<DeviceInfo> getList(String[] columnNames, String[] columnValues, int page) {
        List<DeviceInfo> dataList = new ArrayList<>();
        StringBuilder selectionBuilder = new StringBuilder();
        Cursor cursor = null;
        selectionBuilder.append(SELECT_LIST_SQL);
        if (columnNames != null && columnValues != null) {
            if (columnNames.length != 0) {
                selectionBuilder.append(" WHERE ");
                for (int i = 0; i < columnNames.length; i++) {
                    selectionBuilder.append(columnNames[i]).append("=?");
                    if (i != columnNames.length - 1) {
                        selectionBuilder.append(" AND ");
                    }
                }
            }
        }
        int offset = (page - 1) * 15;
        selectionBuilder.append(" LIMIT " + LIMIT + " OFFSET ").append(offset);
        try {
            cursor = databaseUtil.rawQuery(selectionBuilder.toString(), columnValues);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    DeviceInfo deviceInfo = new DeviceInfo();
                    int columnIndex = cursor.getColumnIndex("info_id");
                    if (columnIndex >= 0) {
                        deviceInfo.setInfoId(cursor.getInt(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("device_id");
                    if (columnIndex >= 0) {
                        deviceInfo.setDeviceId(cursor.getString(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("type_id");
                    if (columnIndex >= 0) {
                        deviceInfo.setTypeId(cursor.getInt(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("scene_id");
                    if (columnIndex >= 0) {
                        deviceInfo.setSceneId(cursor.getInt(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("firmware_version");
                    if (columnIndex >= 0) {
                        deviceInfo.setFirmwareVersion(cursor.getString(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("on_line");
                    if (columnIndex >= 0) {
                        deviceInfo.setOnLine(cursor.getInt(columnIndex) == 1);
                    }
                    columnIndex = cursor.getColumnIndex("rssi");
                    if (columnIndex >= 0) {
                        deviceInfo.setRssi(cursor.getInt(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("device_data");
                    if (columnIndex >= 0) {
                        deviceInfo.setDeviceData(cursor.getString(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("type_name");
                    if (columnIndex >= 0) {
                        deviceInfo.setTypeName(cursor.getString(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("type_img");
                    if (columnIndex >= 0) {
                        deviceInfo.setTypeImg(cursor.getString(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("scene_name");
                    if (columnIndex >= 0) {
                        deviceInfo.setSceneName(cursor.getString(columnIndex));
                    }
                    columnIndex = cursor.getColumnIndex("scene_icon");
                    if (columnIndex >= 0) {
                        deviceInfo.setSceneIcon(cursor.getString(columnIndex));
                    }
                    dataList.add(deviceInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return dataList;
    }


    /**
     * 获取总记录数
     *
     * @param columnValues
     * @return
     */
    public int getTotalRecordCount(String[] columnNames, String[] columnValues) {
        int count = 0;
        StringBuilder selectionBuilder = new StringBuilder();
        Cursor cursor = null;
        String COUNT_SQL = "SELECT COUNT(*) " +
                "FROM device_info " +
                "LEFT JOIN device_type ON device_info.type_id = device_type.type_id " +
                "LEFT JOIN device_scene ON device_info.scene_id = device_scene.scene_id";
        selectionBuilder.append(COUNT_SQL);
        if (columnNames != null && columnValues != null) {
            if (columnNames.length != 0) {
                selectionBuilder.append(" WHERE ");
                for (int i = 0; i < columnNames.length; i++) {
                    selectionBuilder.append(columnNames[i]).append("=?");
                    if (i != columnNames.length - 1) {
                        selectionBuilder.append(" AND ");
                    }
                }
            }
        }

        try {
            cursor = databaseUtil.rawQuery(selectionBuilder.toString(), columnValues);
            if (cursor != null && cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return count;
    }

}
